# -*- coding: utf-8 -*-
from datetime import datetime
from django import forms

from google.appengine.ext.db import djangoforms
from google.appengine.ext import db

from base.models import Issue, OneClass, School, Booth
from base.util.decorators import render_to, login_required, admin_required

import logging

class IssueForm(djangoforms.ModelForm):
    class Meta:
        model = Issue
        exclude = ('id',)

@admin_required
@render_to('issue/form.html')
def create(request):
    data = request.GET.copy()
    class_id = data.get('class', '').strip()
    school_id = data.get('school', '').strip()
    booth_id = data.get('booth', '').strip()
    if class_id:
        oneclass = OneClass.get_using_id(int(class_id))
        form = IssueForm(initial={'school': oneclass.school.key()})
    elif school_id:
        school = School.get_using_id(int(school_id))
        form = IssueForm(initial={'school': school.key()})
    elif booth_id:
        booth = Booth.get_using_id(int(booth_id))
        form = IssueForm(initial={'booth': booth.key()})
    else:
        form = IssueForm()
    if request.method == 'POST':
        form = IssueForm(request.POST)
        if form.is_valid():
            issue = form.save(commit=False)
            issue.put()
            return issue.get_absolute_url
    return {
            'form': form,
            }

@admin_required
@render_to('issue/detail.html')
def detail(request, issue_id):
    issue = Issue.get_using_id(int(issue_id))
    return {
        'issue': issue,
        }

@admin_required
@render_to('issue/form.html')
def change(request, issue_id):
    issue = Issue.get_using_id(int(issue_id))
    form = IssueForm(request.POST or None, instance=issue)
    if form.is_valid():
        issue = form.save()
        return issue.get_absolute_url
    return {'form': form}

@admin_required
@render_to('issue/list.html')
def list(request):
#    query = Issue.gql('WHERE year=:year ORDER BY month ASC', year=int(year))
#    issue = query.fetch(100)
    issues = Issue.all()
    return {'issues': issues}